package com.wangzeqi.changliaoba.contacts;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.wangzeqi.changliaba.dao.AddPersonEntity;
import com.wangzeqi.changliaba.dao.AddPersonEntityDao;
import com.wangzeqi.changliaba.dao.ContactsEntity;
import com.wangzeqi.changliaba.dao.ContactsEntityDao;
import com.wangzeqi.changliaoba.BuildConfig;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 16/3/3.
 */
public class AddPersonActivity extends BaseActivity implements View.OnClickListener {

    private EditText editText;

    private Button button;
    private TextView textView, textViewAdd;
    private RelativeLayout relativeLayout;
    private ProgressDialog progressDialog;
    private AddPersonAdapter addPersonAdapter;
    private ListView listView;
    private AddPersonEntity personEntity;
    private List<AddPersonEntity> datas;
    QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder();
    private ImageButton imageBtn;
    List<AddPersonEntity> listPerson;


    String data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_person_dialog_layout);
        editText = (EditText) findViewById(R.id.find_person_et);
        button = (Button) findViewById(R.id.find_person_btn);
        button.setOnClickListener(this);
        textView = (TextView) findViewById(R.id.find_person_tv);
        textViewAdd = (TextView) findViewById(R.id.add_person_tv);
        textViewAdd.setOnClickListener(this);
        relativeLayout = (RelativeLayout) findViewById(R.id.rl_find_person);
        addPersonAdapter = new AddPersonAdapter(this);
        listView = (ListView) findViewById(R.id.add_person_list);
        listView.setAdapter(addPersonAdapter);
        imageBtn = (ImageButton) findViewById(R.id.back_btn);
        imageBtn.setOnClickListener(this);
        EMChat.getInstance().init(this);
        EMChat.getInstance().setDebugMode(true);
        EMChatOptions options = EMChatManager.getInstance().getChatOptions();
        options.setAcceptInvitationAlways(false);
        options.setUseRoster(true);
        EMChat.getInstance().setAppInited();
        monitorFriend();
        datas = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder().where(AddPersonEntityDao.Properties.User_name_key.eq(EMChatManager.getInstance().getCurrentUser())).list();
        addPersonAdapter.addData(datas);

    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_person_btn:
                findPerson();
                break;
            case R.id.add_person_tv:
                addPerson();
                getData();
                addPersonAdapter.notifyDataSetChanged();
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    private void getData() {
        if (qb != null && qb.list().size() > 0) {
            addPersonAdapter.addData(listPerson);
        }
    }

    private void addPerson() {
        if (EMChatManager.getInstance().getCurrentUser().equals(editText.getText().toString())) {
            Toast.makeText(this, "不能添加自己", Toast.LENGTH_SHORT).show();
            return;
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在发送请求");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    final String s = "我想添加你为好友";
                    EMContactManager.getInstance().addContact(editText.getText().toString(), s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            addSendBtn();

                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "请求失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();

    }

    private void addSendBtn() {

        listPerson = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder().where(AddPersonEntityDao.Properties.User_name_key.eq(EMChatManager.getInstance().getCurrentUser())).list();


        for (int i = 0; i < listPerson.size(); i++) {
            if (listPerson.get(i).getName().equals(editText.getText().toString())) {
                data = listPerson.get(i).getName();
            }
        }

        QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder();
        QueryBuilder queryBuilder = AllSingleTon.getOurInstance().getDaoSession().getContactsEntityDao().queryBuilder();
        List<ContactsEntity> list = queryBuilder.where(ContactsEntityDao.Properties.Name.eq(editText.getText().toString())).list();

        if (queryBuilder != null && queryBuilder.list().size() > 0) {
            if (list != null && list.size() > 0) {
                Toast.makeText(this, editText.getText().toString() + "已经是你的好友", Toast.LENGTH_SHORT).show();
            } else if (qb != null && qb.list().size() > 0) {
                Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();

                Log.d("AddPersonActivity******>>>>", "datas:" + data);
                if (data.equals(editText.getText().toString())) {
                    Log.d("AddPersonActivity******>>>", "datas.get(0):" + data);

                } else {
                    initDataPerson();
                }
            } else {
                initDataPerson();
            }
        } else {
            initDataPerson();
        }
    }

    private void initDataPerson() {
        Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
        AddPersonEntity data = new AddPersonEntity(EMChatManager.getInstance().getCurrentUser(), editText.getText().toString(), 1, "");
        AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().insertOrReplace(data);
    }

    private void findPerson() {

        String name = editText.getText().toString().trim();
        if (name != null && name.length() > 0) {
            //若服务器存在此联系人
            //TODO
            relativeLayout.setVisibility(View.VISIBLE);
            textView.setText(editText.getText().toString());

        } else {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();

        }

    }

    private void monitorFriend() {
        EMContactManager.getInstance().setContactListener(new EMContactListener() {

            @Override
            public void onContactAgreed(String username) {
                //好友请求被同意
                Log.d("AddPersonActivity*--->>", username + "同意了你的好友请求");
//                QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder();


                qb.where(AddPersonEntityDao.Properties.User_name_key.eq(EMChatManager.getInstance().getCurrentUser())).list().remove(username);
                AddPersonEntity data = new AddPersonEntity( EMChatManager.getInstance().getCurrentUser(), username, 2, "");
                AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().insertOrReplace(data);


            }

            @Override
            public void onContactRefused(String username) {
                //好友请求被拒绝

            }

            @Override
            public void onContactInvited(String username, String reason) {
                String name = null;
                datas = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder().where(AddPersonEntityDao.Properties.User_name_key.eq(EMChatManager.getInstance().getCurrentUser())).list();

                for (int i = 0; i < datas.size(); i++) {
                    if (datas.get(i).getName().equals(username)){
                        name = datas.get(i).getName();
                    }
                }
                //收到好友邀请
                Log.d("AddPersonActivity------>>>", username + "---请求加你好友---" + reason);

//                QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().queryBuilder();
                if (qb != null && qb.list().size() > 0) {

                    if (name != null  ) {


                    } else {

                        AddPersonEntity data = new AddPersonEntity(EMChatManager.getInstance().getCurrentUser(), username, 3, reason);
                        AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().insertOrReplace(data);

                    }
                } else {

                    AddPersonEntity data = new AddPersonEntity(EMChatManager.getInstance().getCurrentUser(), username, 3, reason);
                    AllSingleTon.getOurInstance().getDaoSession().getAddPersonEntityDao().insertOrReplace(data);

                }
            }

            @Override
            public void onContactDeleted(List<String> usernameList) {
                //被删除时回调此方法

            }

            @Override
            public void onContactAdded(List<String> usernameList) {
                //增加了联系人时回调此方法

            }
        });
    }
}